var skill = {
	save: function() {
		delete this._joiner_map;
		delete this._can_user_draw_lottery;
		delete this._user_win_something;
		db.update(db_table_name, this._id, this);
	},
	getDetail: function() {
		lottery = this;
		lottery.awards.forEach(function(award) {
			switch (award.type) {
				case BusLotteryCon.TYPE.优惠券:
				case BusLotteryCon.TYPE.商品:
					var _Con = require("../" + award.type + "/_con");
					var _content = _Con.get(award.content_id);
					//更新信息
					if (_content) {
						award.content = $Object.clone(_content);
					}
					break;
			}
		});
		return lottery;
	},
	destroy: function() {
		db.remove(db_table_name, this._id);
	},
	isChangeAble: function() {
		return ~~this.state == BusLotteryCon.STATE.未开始;
	},
	setInfo: function(info, is_no_save) {
		is_no_save = !!is_no_save;
		if (this.state <= BusLotteryCon.STATE.进行中) {
			//结束前
			//可以在已经开始的时候延长活动时间
			this.endTime = parseInt(info.endTime) || Number.MAX_VALUE;
			//可以改动每个人的参与次数、参与的时间间隔
			this.visitor_times_limit = parseInt(info.visitor_times_limit) || 1; //默认为1次
			this.visitor_interval_limit = parseInt(info.visitor_interval_limit) || 12 * 60 * 60 * 1000; //默认12小时
			//抽奖活动详细介绍
			this.detail_content = helper.xss(info.detail_content);
			is_no_save || this.save();
		}

		if (!this.isChangeAble()) {
			throwCusError("抽奖活动已经开始无法修改设定");
		}
		//抽奖活动标题
		this.title = String(info.title || "").trim();
		if (!this.title) {
			throwCusError("抽奖活动标题不可为空")
		}
		if (this.title.length > config.lotteryTitleLength) {
			throwCusError("抽奖活动标题长度超过字数限制")
		}
		//抽奖概率与奖品设定
		if (!(Array.isArray(info.awards) && info.awards.length)) {
			throwCusError("奖品不可为空")
		}
		var self = this;
		var awards = info.awards.map(function(award, index) {
			var _award_item = {};
			//奖项名
			_award_item.title = String(award.title || "奖项" + index);
			if (_award_item.title.length > config.lotteryTitleLength) {
				throwCusError("奖品" + (index + 1) + "奖项，名长度超过字数限制")
			}
			//类型
			if (!$Object.hasValue(BusLotteryCon.TYPE, award.type)) {
				throwCusError("奖品" + (index + 1) + " 类型无效")
			}
			_award_item.type = String(award.type);
			//对应对象
			switch (_award_item.type) {
				case BusLotteryCon.TYPE.优惠券:
					var _Con = require("../" + _award_item.type + "/_con");
					var _content = _Con.get(award.content_id);
					if (!_content) {
						throwCusError("奖品" + (index + 1) + " 优惠券ID无效")
					}
					_award_item.content_id = String(award.content_id);
					_award_item.content = $Object.clone(_content);
					break;
				case BusLotteryCon.TYPE.商品:
					var _Con = require("../" + _award_item.type + "/_con");
					var bus = BusCon.get(self.bus_id);
					var _content = bus && bus._getGoods(award.content_id);
					if (!_content) {
						throwCusError("奖品" + (index + 1) + " 商品ID无效")
					}
					_award_item.content_id = String(award.content_id);
					_award_item.content = $Object.clone(_content);
					break;
				case BusLotteryCon.TYPE.自定义:
					var _award_content = award.content;
					if (_award_content && _award_content.title) {
						_award_item.content = {
							title: _award_content.title,
							intro: _award_content.intro,
							img_url: _award_content.img_url
						}
					} else {
						throwCusError("自定义奖品" + (index + 1) + " 信息不完善");
					}
			}
			//奖品发放数量
			_award_item.win_number = ~~award.win_number || 1;
			//预计参与人数
			_award_item.join_number = ~~award.join_number || 1;

			//已经发放的奖品记录
			_award_item.winner_list = [];

			return _award_item;
		});
		//中奖概率从低到高排列，一等奖排在最前面，参与奖排在最后面
		awards.sort(function(_award_item_a, _award_item_b) {
			return (_award_item_a.win_number / _award_item_a.join_number) > (_award_item_b.win_number / _award_item_b.join_number)
		});
		this.awards = awards;
		//开始时间
		this.startTime = parseInt(info.startTime) || 0;

		is_no_save || this.save();
	},
	// _nextFlowStatus: function() {
	// 	var state = +this.state;
	// 	if (state || state == 0) {
	// 		//如果有下一个状态值，进入
	// 		if ($Object.hasValue(BusLotteryCon.STATE, state + 1)) {
	// 			state += 1;
	// 		}
	// 	} else {
	// 		throwCusError("未知的抽奖状态")
	// 	}
	// 	this.state = state;
	// 	this.save();
	// 	return state;
	// },
	_startLotteryGame: function() {
		if (!this.state === BusLotteryCon.STATE.未开始) {
			throwCusError("抽奖已经进行，不可重新开始")
		}
		this.state = BusLotteryCon.STATE.未开始;
		this.save();
	},
	//进行抽奖
	_addJoinNumber: function(visitor_id) {
		var _now = Date.now();
		if (!visitor_id) {
			throwCusError("抽奖者信息不可为空");
		}
		//检查抽奖活动的状态
		if (this.state < BusLotteryCon.STATE.进行中) {
			if (_now >= this.startTime) { //到了开始时间，开始抽奖
				this.state = BusLotteryCon.STATE.进行中;
			} else {
				throwCusError("抽奖活动还未开始")
			}
		}
		if (this.state > BusLotteryCon.STATE.进行中 || _now > this.endTime) {
			throwCusError("抽奖活动已经结束")
		}
		//检查抽奖记录
		if (this.joiner_map.hasOwnProperty(visitor_id)) {
			var joiner_times_info = this.joiner_map[visitor_id];
			if (joiner_times_info.length >= this.visitor_times_limit) {
				throwCusError("用户的参与次数已经打到上限")
			} else if ((_now - joiner_times_info[joiner_times_info.length - 1]) < this.visitor_interval_limit) {
				throwCusError("下一次抽奖的时间点还未到达")
			}
			joiner_times_info.push(_now);
		} else {
			this.joiner_map[visitor_id] = [_now];
		}
		//当前抽奖的参与人
		var joined_numner = this.joined_numner += 1;
		var win_something;
		//对各个奖品进行参与抽奖
		//奖品的排序是从低到高
		this.awards.some(function(_award_item) {
			if (_award_item.winner_list.length >= _award_item.win_number) {
				return
			}
			//为了让参与人数尽可能逼近额定的参与人数，概念采取不均匀，越接近中奖点概念越高

			//中奖点分布
			var win_point_loop = _award_item.join_number / _award_item.win_number;
			//当前参与者在中奖点的中奖概率，越接近当前中奖点中奖概率越高，到中奖点了就有50%的概率中奖
			var win_rate = (joined_numner - _award_item.winner_list.length * win_point_loop) / (win_point_loop * 2);
			console.log(_award_item.title, win_rate)
			if (Math.random() < win_rate) { //中奖了
				_award_item.winner_list.push(visitor_id);
				win_something = $Object.clone(_award_item);
				delete win_something.winner_list; //不透露其它中奖者的信息
				return true; //结束抽奖
			}
		});
		this.save();
		return win_something;
	}
};

module.exports = skill;

var db = require("../db/index");
var UserCon = require("./_con");
var BusCon = require("../bus/_con");
var GoodsCon = require("../goods/_con");
var AchCon = require("../ach/_con");
var BusLotteryCon = require("../bus.lottery/_con");
var BuffCon = require("../buff/_con");
var config = require("../_include/config");
var data_cut = require("../_include/data_cut");
var $Array = require("../_include/$.Array");
var $Object = require("../_include/$.Object");
var helper = require("../_include/helper");
var db_table_name = config.dbname.busLottery;
var db_id_prefix = config.dbIdPrefix.busLottery;